﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Practices.Unity;

namespace ERPStore.Host.IOC
{
	public class UnityServiceDependencyResolver : System.Web.Http.Dependencies.IDependencyResolver
	{
		Microsoft.Practices.Unity.IUnityContainer m_Container;
		ERPStore.Logging.ILogger m_Logger;
		System.Web.Http.Dependencies.IDependencyResolver m_DefaultResolver;

		public UnityServiceDependencyResolver(Microsoft.Practices.Unity.IUnityContainer container, System.Web.Http.Dependencies.IDependencyResolver defaultResolver)
		{
			m_Container = container;
			m_Logger = m_Container.Resolve<ERPStore.Logging.ILogger>();
			m_DefaultResolver = defaultResolver;
		}

		public System.Web.Http.Dependencies.IDependencyScope BeginScope()
		{
			// This example does not support child scopes, so we simply return 'this'.
			return this;
		}

		public object GetService(Type serviceType)
		{
			m_Logger.Debug("Resolve type : {0}", serviceType.FullName);
			if (IsBuiltIn(serviceType))
			{
				return m_DefaultResolver.GetService(serviceType);
			}
			return m_Container.Resolve(serviceType);
		}

		public IEnumerable<object> GetServices(Type serviceType)
		{
			m_Logger.Debug("Resolve type list of : {0}", serviceType.FullName);
			if (IsBuiltIn(serviceType))
			{
				return m_DefaultResolver.GetServices(serviceType);
			}

			return m_Container.ResolveAll(serviceType);
		}

		private bool IsBuiltIn(Type serviceType)
		{
			if (serviceType == typeof(System.Web.Http.Tracing.ITraceManager)
				|| serviceType == typeof(System.Web.Http.Tracing.ITraceWriter)
				|| serviceType == typeof(System.Web.Http.Dispatcher.IHttpControllerSelector)
				|| serviceType == typeof(System.Web.Http.Dispatcher.IAssembliesResolver)
				|| serviceType == typeof(System.Net.Http.Formatting.IContentNegotiator)
				|| serviceType == typeof(System.Web.Http.Dispatcher.IHttpControllerTypeResolver)
				|| serviceType == typeof(System.Web.Http.Dispatcher.IHttpControllerActivator)
				|| serviceType == typeof(System.Web.Http.Controllers.IHttpActionSelector)
				|| serviceType == typeof(System.Web.Http.Controllers.IHttpActionInvoker)
				|| serviceType == typeof(System.Web.Http.Controllers.IActionValueBinder)
				|| serviceType == typeof(System.Web.Http.Validation.IBodyModelValidator)
				|| serviceType == typeof(System.Web.Http.Metadata.ModelMetadataProvider)
				|| serviceType == typeof(System.Web.Http.Hosting.IHostBufferPolicySelector)
				|| serviceType == typeof(System.Web.Http.Description.IApiExplorer)
				|| serviceType == typeof(System.Web.Http.Description.IDocumentationProvider)
				|| serviceType.FullName.Equals("System.Web.Http.Validation.IModelValidatorCache")
				)
			{
				return true;
			}
			return false;
		}

		public void Dispose()
		{
		}
	}
}
